package ntd.util.frame.javacv;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.cron.CronUtil;
import cn.hutool.log.StaticLog;
import com.modular.extra.ai.FactoryAiOpt;
import ntd.sys.ToolJvm;
import ntd.tool.ToolCron;
import ntd.util.UtilCatch;
import ntd.util.UtilThreadPool;
import ntd.util.frame.javacv.action.bean.VisionModelDo;
import ntd.util.frame.javacv.bo.CameraBO;
import ntd.util.frame.javacv.config.AiConfig;
import ntd.util.frame.javacv.remote.AiVisionRemote;
import ntd.util.frame.javacv.tool.ToolFtpSync;
import ntd.util.frame.javacv.vlc.FactoryVlc;
import com.c.Constant;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import static ntd.util.frame.javacv.ComVisionApi.initAiRemote;

public class ImgTask {

    private static int aiRemoteIndex = 0;

    private final static int cycleTime = 30;

    public static void main(String[] args) throws Exception {
        ToolJvm.setNoExit();
//        startTask();
//        AiFilePush.start();
//        AiFilePush.fileSyncDown();
//        initAiServer().get(0).initFtpSync().downloadSync("/" + AiConfig.AI_RES_BASE_JSON_PATH_PERSON);
        // AI图片轮询分析任务
        CronUtil.schedule("30 * * * * *", (Runnable) ImgTask::startTask);

        ToolCron.initTask();
    }

    public static void startTask() {
        Map<String, byte[]> imgMap = new HashMap<>();
        CountDownLatch countDownLatch = ThreadUtil.newCountDownLatch(ComVisionApi.initCameraList().size());
        for (int i = 0; i < ComVisionApi.initCameraList().size(); i++) {
            int finalI = i;
            ThreadUtil.execAsync(() -> UtilCatch.tryCatchNoRes(() -> {
                CameraBO cameraBO = ComVisionApi.initCameraList().get(finalI);
//                imgMap.put(cameraBO.getCode(), ToolFFmpeg.getKeyImg(cameraBO.getRstpUrl()));
                imgMap.put(cameraBO.getCode(), FactoryVlc.getSnapshotAboutBytes(cameraBO.initRtspUrl()));
                StaticLog.info("监控[{}][{}]图片帧获取完成", cameraBO.getCameraMn(), cameraBO.getCameraName());
            }, countDownLatch::countDown));
        }
        UtilCatch.tryCatchNoRes(countDownLatch::await);

        int index = 0;

        for (VisionModelDo visionModelDo : FactoryAiOpt.OPT_VISION_MODEL.cacheListAll()) {
            // todo 这个逻辑需要调整或者删除
            List<CameraBO> modeCameras = CollectionUtil.filter(ComVisionApi.initCameraList(), cameraBO -> cameraBO.getModeTypes().contains(visionModelDo.getCode()));
            if (CollectionUtil.isNotEmpty(modeCameras)) {
                String currentDate = DateUtil.format(DateUtil.date(), Constant.DATE_FORMAT_WLW_TWO);
                String currentDateDay = DateUtil.format(DateUtil.date(), Constant.DATE_FORMAT_WLW_FOUR);

                String path = StrUtil.format("{}/{}-{}-{}", AiConfig.LOCAL_BASE_DATA_PATH, visionModelDo.getName(), currentDateDay, IdUtil.simpleUUID());

                AiVisionRemote aiVisionRemote = initAiRemote().get(aiRemoteIndex++ % initAiRemote().size());
                ToolFtpSync toolFtpSync = aiVisionRemote.getFtpSync();

                CountDownLatch countDownLatchUp = ThreadUtil.newCountDownLatch(modeCameras.size());
                for (CameraBO modeCamera : modeCameras) {
                    ThreadUtil.execAsync(() -> UtilCatch.tryCatchNoRes(() -> {
                        String imgName = StrUtil.format("{}-{}-{}-{}-image.jpg", modeCamera.getCameraMn(), modeCamera.getCode(), currentDate,
                                visionModelDo.getName());
                        toolFtpSync.upload(path, imgName, imgMap.get(modeCamera.getCode()));
                    }, countDownLatchUp::countDown));
                }
                UtilCatch.tryCatchNoRes(countDownLatchUp::await);

                // 调用分析
                UtilThreadPool.delayRun(() -> aiVisionRemote.analyse(path, visionModelDo.getName(),visionModelDo.getPortNormal()), index++ * 5);
            }
        }
    }
}
